import { responseItemTranformer } from './item'
import { layoutsTransformer } from './layout'

export const graphDataTransformer = data => {
  // 1. 确保data是对象（避免null/undefined）
  const safeData = data || {};

  // 2. 提取字段并显式处理null（关键修复）
  const projectId = safeData.projectId;
  // 若nodes是null/非数组，强制转为空数组
  const nodes = Array.isArray(safeData.nodes) ? safeData.nodes : [];
  // 若relations是null/非数组，强制转为空数组
  const relations = Array.isArray(safeData.relations) ? safeData.relations : [];
  // 处理layout，避免null
  const layout = Array.isArray(safeData.layout) ? safeData.layout : [];

  const layouts = layoutsTransformer(layout);

  return {
    projectId,
    // 现在可以安全调用map()，因为nodes和relations一定是数组
    nodes: nodes.map(n => responseItemTranformer('node', n)),
    links: relations.map(r => responseItemTranformer('link', r)),
    layouts
  }
}
